package com.czx.job;

import com.czx.common.constants.RedisKeys;
import com.czx.common.pool.BlogExecutors;
import com.czx.service.PostScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


@Component
public class PostScoreUpdateJob {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private PostScoreService postScoreService;


    @Scheduled(cron = "0/50 * * * * *")
    public void computeScore() throws InterruptedException {
        BlogExecutors.getPoll().submit(() -> {
            //查询需要计算分数的帖子数量
            Long size = stringRedisTemplate.opsForSet().size(RedisKeys.POST_SCORE_KEY);
            //判断帖子数量是否为空
            if (size == 0) {
                //本次任务没有要更新的帖子
                return;
            }
            //弹栈
            for (int i = 0; i < size; i++) {
                String postId = stringRedisTemplate.opsForSet().pop(RedisKeys.POST_SCORE_KEY);
                if (postId == null) {
                 postId="0";

                }
                //计算分数
                postScoreService.computeScore(Integer.parseInt(postId));
            }
        });
    }

}
